package models

import (
	"context"
	"go-chain-api/global"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type EmailCode struct {
	UserId    string `bson:"userId" json:"userId"`
	Code      string `bson:"code" json:"code"`
	Email     string `bson:"email" json:"email"`
	Timestamp uint64 `bson:"timestamp" json:"timestamp"`
}

func (e EmailCode) Create(emailCode EmailCode) error {
	emailClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("email_code")
	_, err := emailClient.InsertOne(context.TODO(), emailCode)
	if err != nil {
		return err
	}
	return nil
}

func (e EmailCode) GetLatest(email string) (EmailCode, error) {
	var emailCode EmailCode
	emailClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("email_code")

	optionsFind := options.FindOne()
	optionsFind.SetSort(bson.D{{"_id", -1}})
	err := emailClient.FindOne(context.TODO(), bson.M{"email": email}, optionsFind).Decode(&emailCode)
	return emailCode, err
}
